package cn.agilean.test.service;

import cn.agilean.test.entity.Company;
import cn.agilean.test.entity.Relation;
import cn.agilean.test.repo.CompanyRepo;
import cn.agilean.test.vo.CompanyVo;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class CompanyManager {
    private CompanyRepo companyRepo;

    public CompanyManager(CompanyRepo companyRepo) {
        this.companyRepo = companyRepo;
    }

    public List<CompanyVo> findAll() {
        return Collections.emptyList();
    }

    public List<CompanyVo> getCompaniesForNoParent(){
        List<CompanyVo> result = new ArrayList<>();

        // 获取所有公司以及关系
        List<Company> companies = companyRepo.getCompanies();
        List<Relation> relationShips = companyRepo.getRelationShips();

        //获取所有有父类关系的公司id
        List<String> ids = relationShips.stream().map(t -> t.getCompanyId()).collect(Collectors.toList());

        // 获取公司id以及父类id
        Map<String, String> map = relationShips.stream().collect(Collectors.toMap(Relation::getCompanyId,
            Relation::getParentId));
        for(Company company:companies){
            CompanyVo companyVo = new CompanyVo();
            companyVo.setId(company.getId());
            companyVo.setName(company.getName());
            //  如果有父类
            if(ids.contains(company.getId())){
                String parentId = map.get(company.getId());
                for(Company companyParent:companies){
                    if(companyParent.getId().equals(parentId)){
                        CompanyVo companyForParent = new CompanyVo();
                        companyForParent.setId(companyParent.getId());
                        companyForParent.setName(companyParent.getName());
                        companyVo.setParent(companyForParent);
                    }
                }
            }
            result.add(companyVo);
        }
        return result;
    }
}
